import java.util.LinkedList;
import java.util.Queue;

/**
 * 两个队列实现栈
 */
public class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;
    public int usedSize;
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    /**
     * 入栈
     * @param x
     */
    public void push(int x) {
        if (!queue1.isEmpty()){
            queue1.offer(x);
        } else if (!queue2.isEmpty()) {
            queue2.offer(x);
        }else {
            queue1.offer(x);
        }
        usedSize++;
    }

    /**
     * 出栈
     * @return
     */
    public int pop() {
        if (empty()){
            return -1;
        }
        int cur = 0;
        if (!queue1.isEmpty()) {
            cur = queue1.size();
            for (int i = 0; i < cur-1; i++) {
                queue2.offer(queue1.poll());
            }
            usedSize--;
            return queue1.poll();
        }else {
            cur = queue2.size();
            for (int i = 0; i < cur-1; i++) {
                queue1.offer(queue2.poll());
            }
            usedSize--;
            return queue2.poll();
        }
    }

    // 就是peek() 查看栈顶元素
    public int top() {
        if (empty()){
            return -1;
        }
        int cur = 0;
        int ret = 0;
        if (!queue1.isEmpty()) {
            cur = queue1.size();
            for (int i = 0; i < cur; i++) {
                ret = queue1.poll();
                queue2.offer(ret);
            }
            return ret;
        }else {
            cur = queue2.size();
            for (int i = 0; i < cur; i++) {
                ret = queue2.poll();
                queue1.offer(ret);
            }
            return ret;
        }
    }

    /**
     * 是否为空
     * @return
     */
    public boolean empty() {
        return usedSize == 0;
    }

    public boolean empty2() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}
